#include <head.h>

int main(int argc, char const *argv[])
{
    if(argc < 2){
        ERROR("参数不够");
        exit(-1);
    }
    //打开被读取文件 
    int fd = open(argv[1],O_RDONLY);
    if(-1 == fd ){
        ERROR("文件打开失败");
        exit(-1);
    }
    printf("%d",fd);
    //打开一个新文件
    int fd1 = open("new.txt",O_WRONLY | O_CREAT | O_TRUNC, 0666);
    if(-1 == fd1 ){
        ERROR("文件打开失败");
        exit(-1);
    }
    //获取文件大小
    int len = lseek(fd,0,SEEK_END);
    printf("文件大小 %d\n",len);
    //取中间值
    int ave = len / 2;
    printf("中间值 %d \n",ave);
    //缓冲区
    char buff[256] = {0};
    pid_t pid = fork();
    if(pid < 0){
        ERROR("创建进程失败");
        exit(-1);
    }else if( 0 == pid ){
        printf("我是子进程\n");
        int flag = 0;
        lseek(fd , 0 , SEEK_SET);
        while( (flag+sizeof(buff)) <(ave) && (len > 0)){
            //读取文件前一半内容到文件中 
            int read_size = read(fd,buff,sizeof(buff));
            if(read_size <= 0)break;
            write(fd1,buff,read_size);
            memset(buff,0,sizeof(buff));
            flag += sizeof(buff);
            printf("前一段\n");
            }
        read(fd,buff,ave-flag);
        write(fd1,buff,ave-flag);
        
        exit(10);
        
    }
    pid_t pid00 = fork();
    if(pid00 < 0){
        ERROR("进程2创建失败\n");
        exit(-1);
    }else if( 0 == pid00){
        sleep(2);
        //文件光标偏移
        lseek(fd,ave,SEEK_SET);
        printf("我是子进程2\n");
        
        //读取后一半内容到文件中
        while(ave > 0){//注意read 返回值是 读取的字符大小
        //strlen不会自动添加字符串结束符号
            int read_len = read(fd,buff,sizeof(buff));
            if(read_len <= 0)break;//如果读到文件尾 或读取失败
            write(fd1,buff,read_len);
            memset(buff,0,sizeof(buff));
            printf("后一段 \n");
            ave -= read_len;
            sleep(1);
        }
    }
    printf("我是父进程\n");
    waitpid(pid,NULL,0);
    waitpid(pid00,NULL,0);
    //关闭两个文件
    close(fd);
    close(fd1);

    printf("hello world");
    
}